package com.qyl.hrm.controller;

import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.qyl.hrm.common.PageConstant;
import com.qyl.hrm.dto.User;
import com.qyl.hrm.service.UserService;
import com.qyl.hrm.utils.ExcelUtils;
import com.qyl.hrm.utils.ImportExcelUtils;
import com.qyl.hrm.utils.PageBean;

@Controller
@RequestMapping("/admin/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping("/toLogin")
	public String toLogin(){
		
		return "login";
	}
	
	@RequestMapping("/login")
	@ResponseBody
	public Map<String,String> login(User user,HttpSession session,String code){
		
		Map<String,String> map = new HashMap<String, String>();
		
		//从session中取验证码
		String sessionCode = (String) session.getAttribute(PageConstant.AUTH_CODE);
		
		if(sessionCode.equals(code)){
			
			//验证码相同，调用service查询用户是否存在
			User loginUser = userService.getUserByNameAndPwd(user);
			
			//用户存在，返回登录成功
			if(loginUser != null){
				
				map.put("status", "success");
				//把用户放到session中
				session.setAttribute(PageConstant.SESSION_USER, loginUser);
			}else{
				map.put("status", "fail");
				map.put(PageConstant.TIP, "用户账号或密码错误");
			}
			
		}
		
		return map;
	}
	@RequestMapping("/toHome")
	public String toHome(){
		
		return "home";		
	}
	@RequestMapping("/toLeft")
	public String toLeft(){
		
		return "left";		
	}
	@RequestMapping("/toRight")
	public String toRight(){
		
		return "right";		
	}
	@RequestMapping("/toTop")
	public String toTop(){
		
		return "top";		
	}
	
	/**
	 * 用户列表
	 */
	@RequestMapping("/userList")
	public String userList(User user,Integer pageIndex,Integer pageSize,ModelMap map){
		
		//调用service查询总记录数
		Integer recordCount = userService.getRecordCount(user);
		
		PageBean pageBean = new PageBean(pageIndex, recordCount, pageSize);
		
		//调用service获得带有user列表的pageBean
		userService.getUserList(user,pageBean);
		
		//返回数据到页面
		map.put("pageBean", pageBean);		
		map.put("backUser", user);
		
		return "user/userList";
	}
	@RequestMapping("/toAddUser")
	public String toAddUser(){
		
		return "user/addUser";
	}
	
	/**
	 * 保存用户
	 */
	@RequestMapping("/addUser")
	public String addUser(User user,ModelMap map){

		user.setCreate_date(new Date());
				
		int count = userService.addUser(user);		
		
		if(count > 0){
			map.put(PageConstant.TIP, "添加用户成功");
		}else{
			map.put(PageConstant.TIP, "添加用户失败");			
		}	
		return "user/addUser";
	}
	
	@RequestMapping("/deleteUser")
	public String deleteUser(Integer id,ModelMap map){
		
		int count = userService.deleteUser(id);
		
		if(count > 0){
			map.put(PageConstant.TIP, "删除用户成功");
		}else{
			map.put(PageConstant.TIP, "删除用户失败");			
		}	
		return "forward:userList";		
	}
	@RequestMapping("/toUpdateUser")
	public String toUpdateUser(Integer id,ModelMap map){
		
		User user = userService.getUserById(id);
		
		map.put("user", user);
		
		return "user/updateUser";
	}
	@RequestMapping("/updateUser")
	public String updateUser(User user,ModelMap map){
		
		user.setCreate_date(new Date());
		
		int count = userService.updateUser(user);
		
		if(count > 0){
			map.put(PageConstant.TIP, "删除用户成功");
		}else{
			map.put(PageConstant.TIP, "删除用户失败");			
		}	
		return "forward:toUpdateUser";
	}
	
	@RequestMapping("/exportUser")
	public void exportUser(HttpServletRequest request,HttpServletResponse response){
		
		List<User> userList = userService.getAllUsers();
		
		String excelFileName = "用户列表";
		
		String sheetName = "用户信息";
		
		String[] titles = {"name","pass_word","status","create_date"};
		
		try {
			ExcelUtils.exportExcel(excelFileName, sheetName, titles, userList, response, request);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}		
	}
	
	@RequestMapping("/toImportUser")
	public String toImportUser(){

		return "/user/importExcel";
	}
	
	@RequestMapping("importUser")
	public String importUser(MultipartFile userFile,ModelMap map) throws Exception{
		int count = 0;
		try {
			
			if(userFile == null){
				throw new Exception("文件不存在");
			}
			
			InputStream inputStream = userFile.getInputStream();
			
			List<List<Object>> list = new ImportExcelUtils().getBankListByExcel(inputStream, userFile.getOriginalFilename());
			
			List<User> userList = new ArrayList<User>();
			SimpleDateFormat sdf1 = new SimpleDateFormat ("EEE MMM dd HH:mm:ss Z yyyy", Locale.UK);
			for (List<Object> list2 : list) {
				User user = new User();
				user.setName((String) list2.get(0));
				user.setPass_word((String) list2.get(1));
				user.setStatus(Integer.parseInt((String) list2.get(2)));
				Date parse = sdf1.parse((String) list2.get(3));
				user.setCreate_date(parse);
				userList.add(user);
			}
			
			count = userService.saveAllUser(userList);
		
		} catch (Exception e) {

			e.printStackTrace();		}
	
		if(count > 0){
			map.put(PageConstant.TIP, "删除用户成功");
		}else{
			map.put(PageConstant.TIP, "删除用户失败");			
		}	
		
		return "/user/importExcel";
		
	}
}
